package com.aj.activity;

import java.util.Calendar;
import java.util.List;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.aj.activity.adapter.ContantAdapter;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.FamilyDao;
import com.aj.databases.dao.HomeDao;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.Family;
import com.aj.databases.entry.Home;
import com.aj.databases.entry.User;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.CreateTaskRequest;
import com.aj.http.request.HomeRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.HomeResponse;

public class CreateTaskActvity extends BaseActivity implements
		OnWheelChangedListener {

	private static final String TAG = CreateTaskActvity.class.getName();

	private RadioGroup send_task_radiogroup;
	private WheelView id_year;
	private WheelView id_mouth;
	private WheelView id_date;
	private ListView contanctlis;
	private EditText enter_pray_edittext;
	private EditText content_edittext;
	private Button sendbutton;
	private String[] mYearData;
	private String[] mMothData;
	private String[] mDateData;
	private List<Home> homeList;
	private FamilyDao familyDao;
	private HomeDao homeDao;
	private UserDao userDao;
	private User user;
	private ContantAdapter contantAdapter;

	private Calendar calendar;

	private int year;
	private int mouth;
	private int date;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_createtask);
		setActionBarTitle("新建任务");
		initView();
	}

	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0x00001:
				CheckBox checkBox = (CheckBox) msg.obj;
				checkBox.setChecked(!checkBox.isChecked());
				break;
			}
			return true;
		}
	});

	private void initView() {
		familyDao = new FamilyDao(this);
		homeDao = new HomeDao(this);
		userDao = new UserDao(this);
		send_task_radiogroup = (RadioGroup) findViewById(R.id.send_task_radiogroup);
		id_year = (WheelView) findViewById(R.id.id_year);
		id_mouth = (WheelView) findViewById(R.id.id_mouth);
		id_date = (WheelView) findViewById(R.id.id_date);
		contanctlis = (ListView) findViewById(R.id.contanctlis);
		enter_pray_edittext = (EditText) findViewById(R.id.enter_pray_edittext);
		content_edittext = (EditText) findViewById(R.id.content_edittext);
		sendbutton = (Button) findViewById(R.id.sendbutton);
		calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		mouth = calendar.get(Calendar.MONTH) + 1;
		date = calendar.get(Calendar.DATE);
		initDatas();
		id_year.setViewAdapter(new ArrayWheelAdapter<String>(this, mYearData));
		id_mouth.setViewAdapter(new ArrayWheelAdapter<String>(this, mMothData));
		id_date.setViewAdapter(new ArrayWheelAdapter<String>(this, mDateData));

		id_year.addChangingListener(this);
		id_mouth.addChangingListener(this);
		id_date.addChangingListener(this);

		id_year.setVisibleItems(5);
		id_mouth.setVisibleItems(5);
		id_date.setVisibleItems(5);
		updateYear();
		updateMoth();
		updateDate();
		user = userDao.getCurrentUser(LoveHomeApplication.token);

		// contanctlis.setOnItemClickListener(new OnItemClickListener() {
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// ContantAdapter.ViewHolder viewHolde = (ContantAdapter.ViewHolder)
		// view
		// .getTag();
		// Message message = handler.obtainMessage();
		// message.what = 0x00001;
		// message.obj = viewHolde.choose_user;
		// handler.sendMessage(message);
		// }
		// });

		sendbutton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (contantAdapter == null
						|| contantAdapter.getChooseFamilyList() == null
						|| contantAdapter.getChooseFamilyList().size() == 0) {
					Toast.makeText(CreateTaskActvity.this, "请选择需要给谁发布任务~",
							Toast.LENGTH_LONG).show();
					return;
				}
				if (content_edittext.getText().toString().trim().equals("")) {
					Toast.makeText(CreateTaskActvity.this, "请填写任务内容~",
							Toast.LENGTH_LONG).show();
					return;
				}
				String timeString = "" + (id_year.getCurrentItem() + 1900)
						+ "-" + (id_mouth.getCurrentItem() + 1) + "-"
						+ (id_date.getCurrentItem() + 1);
				List<Family> familyList = contantAdapter.getChooseFamilyList();
				String toUserIds = "";
				for (Family family : familyList) {
					toUserIds += family.getUserid() + ",";
				}
				toUserIds = toUserIds.substring(0, toUserIds.lastIndexOf(","));
				showProgressDialog();
				if (send_task_radiogroup.getCheckedRadioButtonId() == R.id.immediatelysend) {
					timeString = null;
				}
				new CreateTaskRequest().excute(CreateTaskActvity.this, null,
						null, content_edittext.getText().toString(),
						user.getUser_id(), timeString, "0", toUserIds,
						new IHttpCallBack() {
							@Override
							public void success(String result) {
								dimissProgressDialog();
								try {
									Common common = new Common(new JSONObject(
											result));
									if (common.getReturnCode() != null
											&& common
													.getReturnCode()
													.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
										finish();
									}
									Toast.makeText(CreateTaskActvity.this,
											common.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String result) {
								dimissProgressDialog();
								try {
									Common common = new Common(new JSONObject(
											result));
									Toast.makeText(CreateTaskActvity.this,
											common.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (LoveHomeApplication.token != null
				&& LoveHomeApplication.token.trim().length() > 0) {
			if (user != null) {
				new HomeRequest().excute(CreateTaskActvity.this,
						user.getUser_id(), "50", "0", new IHttpCallBack() {
							@Override
							public void success(String result) {
								try {
									HomeResponse homeResponse = new HomeResponse(
											new JSONObject(result));
									if (homeResponse != null) {
										Common common = homeResponse
												.getCommon();
										if (common != null) {
											if (common
													.getReturnCode()
													.trim()
													.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
												homeList = homeResponse
														.getHomeList();
												for (Home home : homeList) {
													home = homeDao.insert(home);
													if (home.getFamilyList() != null) {
														for (Family family : home
																.getFamilyList()) {
															familyDao
																	.insert(family);
														}
													}
												}
												List<Family> familyList = familyDao
														.queryFamilyByUserid();
												if (familyList != null
														&& familyList.size() > 0) {
													contantAdapter = new ContantAdapter(
															CreateTaskActvity.this,
															familyList);
													contanctlis
															.setAdapter(contantAdapter);
												}
											} else {
												Log.e(TAG,
														"message:"
																+ common.getErrorMsg());
											}
										}
									}

								} catch (JSONException e) {
								}
							}

							@Override
							public void fail(String result) {
								try {
									Common common = new Common(new JSONObject(
											result));
									if (common != null) {
										Log.e(TAG,
												"message:"
														+ common.getErrorMsg());
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});
			}
		}

	}

	private void updateYear() {
		for (int i = 0; i < mYearData.length; i++) {
			if (year == Integer.parseInt(mYearData[i])) {
				id_year.setCurrentItem(i);
				break;
			}
		}
	}

	private void updateMoth() {
		for (int i = 0; i < mMothData.length; i++) {
			if (mouth == Integer.parseInt(mMothData[i])) {
				id_mouth.setCurrentItem(i);
				initDateData(year, mouth);
				break;
			}
		}
	}

	private void updateDate() {
		for (int i = 0; i < mDateData.length; i++) {
			if (date == Integer.parseInt(mDateData[i])) {
				id_date.setCurrentItem(i);
				break;
			}
		}
	}

	private void initDatas() {
		initYearData();
		initMouthData();
		initDateData(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH) + 1);
	}

	private void initYearData() {
		int yearCount = calendar.get(Calendar.YEAR) - 1899;
		mYearData = new String[yearCount];
		for (int i = 0; i < yearCount; i++) {
			mYearData[i] = (1900 + i) + "";
		}
	}

	private void initMouthData() {
		mMothData = new String[12];
		for (int i = 0; i < 12; i++) {
			mMothData[i] = (i + 1) + "";
		}
	}

	private void initDateData(int year, int mouth) {
		if (mouth == 2) {
			if (isLeapYear(year)) {
				mDateData = new String[29];
				for (int i = 0; i < 29; i++) {
					mDateData[i] = (i + 1) + "";
				}
			} else {
				mDateData = new String[28];
				for (int i = 0; i < 28; i++) {
					mDateData[i] = (i + 1) + "";
				}
			}
		} else {
			switch (mouth) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				mDateData = new String[31];
				for (int i = 0; i < 31; i++) {
					mDateData[i] = (i + 1) + "";
				}
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				mDateData = new String[30];
				for (int i = 0; i < 30; i++) {
					mDateData[i] = (i + 1) + "";
				}
				break;
			}
		}
	}

	private boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? true
				: false;
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (wheel == id_year) {
			initDateData((id_year.getCurrentItem() + 1900),
					(id_mouth.getCurrentItem() + 1));
			id_mouth.setViewAdapter(new ArrayWheelAdapter<String>(this,
					mMothData));
			int current = id_date.getCurrentItem();
			id_date.setViewAdapter(new ArrayWheelAdapter<String>(this,
					mDateData));
			if (current >= mDateData.length) {
				id_date.setCurrentItem(mDateData.length - 1);
			}
		} else if (wheel == id_mouth) {
			initDateData((id_year.getCurrentItem() + 1900),
					(id_mouth.getCurrentItem() + 1));
			int current = id_date.getCurrentItem();
			id_date.setViewAdapter(new ArrayWheelAdapter<String>(this,
					mDateData));
			if (current >= mDateData.length) {
				id_date.setCurrentItem(mDateData.length - 1);
			}
		}
	}
}
